package com.mycomp.cm.controller;

import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.mycomp.cm.dao.ContactDAO;
import com.mycomp.cm.exceptions.UserExistException;
import com.mycomp.cm.model.Contact;
import com.mycomp.cm.model.User;
import com.mycomp.cm.service.UserService;

@Controller
public class UserController {

	private UserService userService;
	private LoginValidator loginValidator;

	@Autowired
	private ContactDAO contactDAO;

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	// User Request Handler Methods

	@Autowired
	public void setLoginValidator(LoginValidator loginValidator) {
		this.loginValidator = loginValidator;
	}

	public void setContactDAO(ContactDAO contactDAO) {
		this.contactDAO = contactDAO;
	}

	@RequestMapping(value = "/userRegister", method = RequestMethod.GET)
	public String getRegisterForm() {
		return "register";
	}

	@RequestMapping(value = "/userRegister", method = RequestMethod.POST)
	public String registerUser(@ModelAttribute("user") User user,
			BindingResult result) {

		try {
			// LoginValidator validator = new LoginValidator();
			// validator.validate(user, result);

			// ValidationUtils.rejectIfEmpty(errors, field, errorCode)

			if (user.getUserName() == null || user.getUserName().length() == 0) {
				result.addError(new ObjectError("uname", "UserName is Required"));
			}
			// if (user.getPassword() == null || user.getPassword().length() ==
			// 0) {
			// result.addError(new ObjectError("pword",
			// "UserName is Required"));
			// }

			if (result.hasErrors()) {
				return "register";
			}

			userService.register(user);

			return "redirect:index.jsp";

		} catch (DataAccessException e) {
		
			UserExistException uee = new UserExistException();
			uee.setUserName(user.getUserName());

		
			
			throw uee;
		}
	}

	//
	@RequestMapping(value = "/userLogin", method = RequestMethod.POST)
	public String name(@ModelAttribute("user") User user, Errors errors,
			HttpSession session) {

		//
		// loginValidator.validate(user, errors);
		//
		// if(errors.hasErrors()){
		//
		// }
		//
		User auser = userService.login(user.getUserName(), user.getPassword());

		if (auser != null) {
			session.setAttribute("cuser", auser);
			return "redirect:cm.htm";
		} else {
			return "redirect:index.jsp";
		}

	}

	@RequestMapping(value = "/cm")
	public ModelAndView cm(HttpSession session) {

		ModelAndView mv = new ModelAndView();

		if (session.isNew()) {
			mv.setViewName("redirect:index.jsp");
			return mv;
		} else {

			Contact contact = new Contact();
			contact.setContEmail("admin@cco.com");

			User user = (User) session.getAttribute("cuser");
			Set<Contact> contacts = userService.getUserContact(user
					.getUserName());

			mv.addObject("userConts", contacts);
			mv.addObject("contact", contact);
			mv.setViewName("cm");

			return mv;

		}

	}

	@RequestMapping(value = "/addContact")
	public String addContact(@ModelAttribute @Valid Contact contact,
			BindingResult result, HttpSession session) {

		if (result.hasErrors()) {
			return "cm";
		} else {
			User user = (User) session.getAttribute("cuser");
			contact.setContactUser(user);
			userService.addContact(contact);
			return "redirect:cm.htm";
		}
	}

	@RequestMapping(value = "/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:index.jsp";
	}

	@RequestMapping(value = "contEdit", params = "contId")
	public String editContact(@RequestParam("contId") int contId, Model model) {
		Contact contact = contactDAO.findByID(contId);
		model.addAttribute("editCont", contact);
		return "updateContact";
	}

	@RequestMapping(value = "/updateContact")
	public String updateContact(
			@ModelAttribute("editCont") @Valid Contact contact,
			BindingResult result, HttpSession session) {

		if (result.hasErrors()) {

			List<ObjectError> errors = result.getAllErrors();
			System.out.println(errors.size());
			for (ObjectError oe : errors) {
				System.out.println(oe.getDefaultMessage());
			}
			return "updateContact";

		} else {
			User user = (User) session.getAttribute("cuser");
			contact.setContactUser(user);
			userService.updateContact(contact);
			return "redirect:cm.htm";
		}
	}

	@RequestMapping(value = "contDelete", params = "contId")
	public String deleteContact(@RequestParam("contId") int contId) {
		contactDAO.delete(contId);
		return "redirect:cm.htm";
	}
	//
	// @ModelAttribute("contactTypes")
	// public List<String> name() {
	// System.out.println("Getting Contacts");
	// List<String> list = new ArrayList<String>();
	// list.add("PERSONAL");
	// list.add("OFFICIAL");
	// return list;
	// }

	// @InitBinder
	// public return_type name() {
	//
	// }

}
